<script setup>
import {onMounted, ref} from "vue";
import {ElMessage} from 'element-plus';
import http from "@/request/Http.js";

// 商品状态映射
const statusMap = {
  0: {text: "下架", type: "info"},
  1: {text: "上架", type: "success"},
  2: {text: "审核中", type: "primary"},
  3: {text: "已售出", type: "warning"},
  4: {text: "已预订", type: "info"}
};
// 审核状态映射
const auditStatusMap = {
  0: {text: "待审核", type: "info"},
  1: {text: "审核通过", type: "success"},
  2: {text: "审核不通过", type: "danger"}
};

// 商品列表
const goodList = ref([]);

//当前页数
const currentPage = ref(1);
// 每页条数
const pageSize = ref(10);
// 总记录数
const total = ref(0);
//总页数
const pages = ref(0);

// 详情弹窗相关
const detailDialogVisible = ref(false);
// 是否在审核模式下
const isAuditing = ref(false);

// 审核表单相关
const auditResult = ref("");
const auditRemark = ref("");
const detailRow = ref(null);

//获取后端商品列表
const getGoodList = async () => {

  //参数拼接
  const params = {
    currentPage: currentPage.value,
    pageSize: pageSize.value
  };

  http.get('/admin/reviewList', {params}).then((response) => {

    // 处理分页信息
    currentPage.value = response.data.currentPage;
    pageSize.value = response.data.pageSize;
    total.value = response.data.total;
    pages.value = response.data.pages;

    if (response.code === 200) {
      goodList.value = response.data.list;
    } else {
      ElMessage.error(response.message || '获取商品列表失败');
    }
  }).catch((error) => {
    console.error('获取商品列表失败:', error);
  });
};

//将处理结果返回给后端
const submitAudit = async () => {

  //参数校验
  if (!detailRow.value.id) {
    ElMessage.error("商品ID不能为空");
    return;
  }

  if (!auditResult.value) {
    ElMessage.error("请选择审核结果");
    return;
  }

  //参数拼接
  const params = new FormData()
  params.append('id', detailRow.value.id)
  params.append('auditStatus', parseInt(auditResult.value))
  params.append('auditRemark', auditRemark.value)

  console.log('提交审核参数:', params.toString());

  http.post('/admin/reviewProduct', params).then((response) => {
    console.log(response);
    if (response.code === 200) {
      ElMessage.success(response.message || '审核商品成功');
      // 刷新商品列表
      getGoodList();
      // 关闭弹窗
      detailDialogVisible.value = false;
    } else {
      ElMessage.error(response.message || '审核商品失败');
    }
  }).catch((error) => {
    console.error('审核商品失败:', error);
  });
};

// 打开详情/审核弹窗（默认为查看模式）
function openDetailDialog(row) {
  //处理图片URL，确保是数组格式
  let imageUrls = [];
  //判断是否为空
  if (!row.imageUrls) {
    imageUrls = [];
  } else if (Array.isArray(row.imageUrls)) {
    imageUrls = row.imageUrls;
  } else if (typeof row.imageUrls === 'string') {
    // 如果是字符串，按逗号分割
    imageUrls = row.imageUrls.split(',').map(url => url.trim()).filter(url => url);
  }

  const processedRow = {
    ...row,
    imageUrls: imageUrls
  };

  detailRow.value = processedRow; // 创建副本以避免修改原数据
  isAuditing.value = false; // 默认为查看模式
  detailDialogVisible.value = true;
}


// 切换到审核模式
function switchToAuditMode() {
  isAuditing.value = true;
  // 初始化审核表单数据
  auditResult.value = detailRow.value.auditStatus === 1 ? "1" : detailRow.value.auditStatus === 2 ? "2" : "";
  auditRemark.value = detailRow.value.auditRemark || "";
}

// 切换回查看模式
function switchToViewMode() {
  isAuditing.value = false;
  // 清空审核表单数据
  auditResult.value = "";
  auditRemark.value = "";
}

// 分页切换
const handleCurrentChange = (page) => {
  currentPage.value = page;
  getGoodList();
};

// 每页条数切换
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1; // 重置到第一页
  getGoodList(); // 重新获取数据
}

//页面加载时获取商品列表
onMounted(() => {
  getGoodList();
});

</script>

<template>
  <div class="audit-page">
    <el-card class="box-card">

      <el-table :data="goodList" border style="width: 100%">
        <el-table-column label="序号" width="60">
          <template #default="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="商品ID" prop="id" width="80"/>
        <el-table-column label="商品名称" prop="name"/>
        <el-table-column label="商品描述" prop="description" show-overflow-tooltip/>
        <el-table-column label="价格" prop="price" width="100">
          <template #default="scope">
            ￥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column label="商品类型" prop="categoryName" width="120"/>
        <el-table-column label="创建时间" prop="createdAt" width="180"/>
        <el-table-column label="审核状态" prop="auditStatus" width="120">
          <template #default="scope">
            <el-tag :type="auditStatusMap[scope.row.auditStatus]?.type">
              {{ auditStatusMap[scope.row.auditStatus]?.text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="openDetailDialog(scope.row)"
            >
              查看/审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-bar">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30]"
            :total="total"
            background
            layout="prev, pager, next, jumper, ->, total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 商品详情/审核弹窗 -->
    <el-dialog
        v-model="detailDialogVisible"
        :title="isAuditing ? '商品审核' : '商品详情'"
        width="600px"
    >
      <el-form class="view-form" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品名称">
              <span>{{ detailRow?.name || '' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格">
              <span>￥{{ detailRow?.price || '' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商品类型">
              <span>{{ detailRow?.categoryName || '' }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间">
              <span>{{ detailRow?.createdAt || '' }}</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-tag :type="statusMap[detailRow?.status]?.type">
                {{ statusMap[detailRow?.status]?.text }}
              </el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核状态">
              <el-tag :type="auditStatusMap[detailRow?.auditStatus]?.type">
                {{ auditStatusMap[detailRow?.auditStatus]?.text }}
              </el-tag>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="商品描述">
          <span>{{ detailRow?.description || '' }}</span>
        </el-form-item>
        <el-form-item v-if="detailRow?.imageUrls && detailRow.imageUrls.length > 0" label="商品图片">
          <div class="image-preview-container">
            <img
                v-for="(img, index) in detailRow.imageUrls"
                :key="index"
                :src="img"
                style="width: 100px; height: 100px; margin-right: 10px; object-fit: cover"
            />
          </div>
        </el-form-item>

        <!-- 审核相关字段（仅在审核模式下显示） -->
        <template v-if="isAuditing">
          <el-form-item label="审核结果" required>
            <el-select v-model="auditResult" placeholder="请选择审核结果">
              <el-option label="审核通过" value="1"/>
              <el-option label="审核不通过" value="2"/>
            </el-select>
          </el-form-item>
          <el-form-item label="审核备注">
            <el-input
                v-model="auditRemark"
                :rows="3"
                placeholder="请输入审核备注"
                type="textarea"
            />
          </el-form-item>
        </template>

        <!-- 审核备注（仅在查看详情模式下显示） -->
        <el-form-item v-else label="审核备注">
          <span>{{ detailRow?.auditRemark || '' }}</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <!-- 查看详情模式下的按钮 -->
          <template v-if="!isAuditing">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
            <el-button
                v-if="detailRow?.auditStatus === 0"
                type="primary"
                @click="switchToAuditMode"
            >
              进行审核
            </el-button>
          </template>

          <!-- 审核模式下的按钮 -->
          <template v-else>
            <el-button @click="switchToViewMode">取消</el-button>
            <el-button type="primary" @click="submitAudit">确定</el-button>
          </template>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.audit-page {
  min-height: 100vh;
  background: #f5f6fa;
  padding: 32px;
}

.box-card {
  max-width: 1400px;
  margin: 0 auto;
  border-radius: 8px;
  box-shadow: 0 2px 8px #f0f1f2;
}


.pagination-bar {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.view-form :deep(.el-form-item__label) {
  font-weight: bold;
}

.view-form :deep(.el-form-item__content) {
  color: #333;
}

.product-image {
  border-radius: 4px;
  cursor: pointer;
}

.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.product-image {
  border-radius: 4px;
  cursor: pointer;
  flex-shrink: 0;
}
</style>